<?php
///////////////////////////////////////////////////////////////////////////

require_once 'lib/hashed_array.php';
require_once 'lib/tv/abstract_tv.php';
require_once 'lib/tv/default_epg_item.php';

require_once 'siol_config.php';
require_once 'siol_exception.php';
require_once 'siol_epg.php';
require_once 'siol_protect.php';

require_once 'siol_channel.php';

///////////////////////////////////////////////////////////////////////////

class SiolTV extends AbstractTv
{
	private $epg;
	private $protect;

    public function __construct()
    {
		hd_print('SiolTV::__construct invoked.');
		$this->epg = new SiolEpg();
		$this->protect = new SiolProtect();
        parent::__construct(
            AbstractTv::MODE_CHANNELS_N_TO_M,
            SiolConfig::TV_FAVORITES_SUPPORTED,
            true);

    }

    public function get_fav_icon_url(&$plugin_cookies)
    {
        return SiolConfig::FAV_CHANNEL_GROUP_ICON_PATH;
    }


    ///////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////

    private static function make_channel_id($media_url)
    {
        $id = preg_replace('/udp:\/\/@/', '', $media_url);
        $id = preg_replace('/:/', '_', $id);
        return $id;
    }

    private static function make_channel_id2($name)
    {
        //$id = preg_replace('/udp:\/\/@/', '', $name);
        //$id = preg_replace('/:/', '_', $id),;
		$fpos1 = strpos($name, ' - ');
		$id = substr($name, $fpos1 + 3);
        return $id;
    }
	
	private static function make_channel_id21($name)
    {
		$fpos1 = strpos($name, ' - ');
		$id = substr($name, 0, $fpos1);
        return $id;
    }
	
    ///////////////////////////////////////////////////////////////////////

    private static function get_icon_path($channel_id)
    { 
		return sprintf(SiolConfig::M3U_ICON_FILE_URL_FORMAT, self::make_channel_id2($channel_id)); 
	}

    ///////////////////////////////////////////////////////////////////////

    protected function load_channels(&$plugin_cookies)
    {
		//hd_print('load_channels invoked.');
        $this->channels = new HashedArray();
        $this->groups = new HashedArray();		

        $all_channels_group = 
            new AllChannelsGroup(
                $this,
                SiolConfig::ALL_CHANNEL_GROUP_CAPTION,
                SiolConfig::ALL_CHANNEL_GROUP_ICON_PATH);

        $this->groups->put($all_channels_group);
		/*
		$this->groups->put(new DefaultGroup(
                '__hd',
                SiolConfig::ALL_CHANNEL_HD_GROUP_CAPTION,
                SiolConfig::ALL_CHANNEL_HD_GROUP_ICON_PATH));
		*/
		/*
		
        $all_channels_low_group = 
            new DefaultGroup(
                'low',
                SiolConfig::ALL_CHANNEL_LOW_GROUP_CAPTION,
                SiolConfig::ALL_CHANNEL_LOW_GROUP_ICON_PATH);

        $this->groups->put($all_channels_low_group);
		*/

        $m3u_lines = file(SiolConfig::M3U_FILE_URL, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

        for ($i = 0; $i < count($m3u_lines); ++$i)
        {

			$fpos3 = strpos($m3u_lines[$i], 'EXTINF:');
			if ($fpos3 == false)
			{
				continue;
			}
			
            //$caption = $matches[1];


            if ($i + 1 >= count($m3u_lines))
			{
                break;
			}
			$fpos1 = strpos($m3u_lines[$i], 'logo=');
			$fpos2 = strpos($m3u_lines[$i], ',');
			if ($fpos1 == false)
			{
				$logo = '';
			}
			else
			{
				$logo = trim(substr($m3u_lines[$i], $fpos1 + 5, $fpos2 - $fpos1 - 5));
			}
			$caption = trim(substr($m3u_lines[$i], $fpos2 + 1));

            $media_url = null;

            for (++$i; $i < count($m3u_lines); ++$i)
            {
                if (preg_match('/^udp:\/\//', $m3u_lines[$i]) == 1)
                {
                    $media_url = $m3u_lines[$i];
                    break;
                }
            }

            if (is_null($media_url))
			{
                break;
			}

			$id = self::make_channel_id($caption);
			//$icon_path = self::get_icon_path($id);
			$icon_path = $logo;
			//hd_print("Adding channel: id: $id, caption: $caption, icon_path: $icon_path");
			$protected_channel = false;
			$original_name = self::make_channel_id2($caption);
			$protected_channel = $this->protect->IsChannelProtected($original_name);
            $channel = new SiolChannel(
                    $id,
                    $caption,
                    $icon_path,
                    $media_url,
                    -1,
                    0,
                    2,
					$protected_channel);
			
            $this->channels->put($channel);
			/*
			$group = $this->groups->get('__hd');
			$channel->add_group($group);
			$group->add_channel($channel);
			*/
        }
		
		
	/*	
        $m3u_lines_low = file(SiolConfig::M3U_FILE_URL_LOW, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

        for ($i = 0; $i < count($m3u_lines_low); ++$i)
        {

			$fpos3 = strpos($m3u_lines_low[$i], 'EXTINF:');
			if ($fpos3 == false)
			{
				continue;
			}
			
            //$caption = $matches[1];


            if ($i + 1 >= count($m3u_lines_low))
			{
                break;
			}
			$fpos1 = strpos($m3u_lines_low[$i], 'logo=');
			$fpos2 = strpos($m3u_lines_low[$i], ',');
			if ($fpos1 == false)
			{
				$logo = '';
			}
			else
			{
				$logo = trim(substr($m3u_lines_low[$i], $fpos1 + 5, $fpos2 - $fpos1 - 5));
			}
			$caption = trim(substr($m3u_lines_low[$i], $fpos2 + 1));

            $media_url = null;

            for (++$i; $i < count($m3u_lines_low); ++$i)
            {
                if (preg_match('/^udp:\/\//', $m3u_lines_low[$i]) == 1)
                {
                    $media_url = $m3u_lines_low[$i];
                    break;
                }
            }

            if (is_null($media_url))
			{
                break;
			}

			$id = self::make_channel_id($caption);
			//$icon_path = self::get_icon_path($id);
			$icon_path = $logo;
			//hd_print("Adding channel: id: $id, caption: $caption, icon_path: $icon_path");
			$protected_channel = false;
			$original_name = self::make_channel_id2($caption);
			if ($original_name == 'RTL II')
			{
				$protected_channel = true;
			}
            $channel = new SiolChannel(
                    $id,
                    $caption,
                    $icon_path,
                    $media_url,
                    -1,
                    0,
                    2,
					$protected_channel);
			
			$group = $this->groups->get('low');
            $this->channels->put($channel);
			$channel->add_group($group);
			$group->add_channel($channel);
        }
		*/
		//hd_print('load_channels finished.');
    }

/*
    protected function load_channels(&$plugin_cookies)
    {
		//hd_print('load_channels invoked.');
        $this->channels = new HashedArray();
        $this->groups = new HashedArray();

        $all_channels_group = 
            new AllChannelsGroup(
                $this,
                SiolConfig::ALL_CHANNEL_GROUP_CAPTION,
                SiolConfig::ALL_CHANNEL_GROUP_ICON_PATH);
		$this->groups->put($all_channels_group);

        $m3u_lines = file(SiolConfig::M3U_FILE_URL, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

        for ($i = 0; $i < count($m3u_lines); ++$i)
        {

			$fpos3 = strpos($m3u_lines[$i], 'EXTINF:');
			if ($fpos3 == false)
			{
				continue;
			}
			
            //$caption = $matches[1];


            if ($i + 1 >= count($m3u_lines))
			{
                break;
			}
			$fpos1 = strpos($m3u_lines[$i], 'logo=');
			$fpos2 = strpos($m3u_lines[$i], ',');
			if ($fpos1 == false)
			{
				$logo = '';
			}
			else
			{
				$logo = trim(substr($m3u_lines[$i], $fpos1 + 5, $fpos2 - $fpos1 - 5));
			}
			$caption = trim(substr($m3u_lines[$i], $fpos2 + 1));

            $media_url = null;

            for (++$i; $i < count($m3u_lines); ++$i)
            {
                if (preg_match('/^udp:\/\//', $m3u_lines[$i]) == 1)
                {
                    $media_url = $m3u_lines[$i];
                    break;
                }
            }

            if (is_null($media_url))
			{
                break;
			}

			$id = self::make_channel_id($caption);
			//$icon_path = self::get_icon_path($id);
			$icon_path = $logo;
			//hd_print("Adding channel: id: $id, caption: $caption, icon_path: $icon_path");
			$protected_channel = false;
			$original_name = self::make_channel_id2($caption);
			if ($original_name == 'RTL II')
			{
				$protected_channel = true;
			}
            $channel = new SiolChannel(
                    $id,
                    $caption,
                    $icon_path,
                    $media_url,
                    -1,
                    0,
                    2,
					$protected_channel);
			$this->channels->put($channel);
        }

	
		//hd_print('load_channels finished.');
    }
*/
    ///////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////

    public function get_day_epg_iterator($channel_id, $day_start_ts, &$plugin_cookies)
    { 
		//hd_print("get_day_epg_iterator invoked. $channel_id, $day_start_ts");
		return array();
	}


	public function get_day_epg($channel_id, $day_start_tm_sec, &$plugin_cookies)
	{
		//hd_print("get_day_epg invoked. $channel_id, $day_start_tm_sec");
		$epg_program = array();
		
		$this->ensure_channels_loaded($plugin_cookies);
		if (!isset($plugin_cookies->SiolPluginShowEpgDetails))
		{
			$plugin_cookies->SiolPluginShowEpgDetails = 'no';
		}
		$days_wanted = floor($day_start_tm_sec / 86400);//round($day_start_tm_sec / 86400, 0, PHP_ROUND_HALF_DOWN);
		$days_current = floor(time() / 86400);//round(time() / 86400, 0, PHP_ROUND_HALF_DOWN);
		//hd_print("epg_date: $days_wanted, now: $days_current");

		$day_str = 1; 
		if ($days_wanted < $days_current)
		{
			$day_str = 0;
		}
		else
		{
			$day_str = $days_wanted - $days_current + 1;
		}
		
		$channel_name = $this->get_channel($channel_id)->get_id();
		//hd_print("channel_name: $channel_name");
		$channel_str = $this->epg->GetChannelStr(self::make_channel_id2($channel_name));
		//hd_print("channel_str: $channel_str");
		$url = sprintf(SiolConfig::EPG_URL_FORMAT, $channel_str, $day_str);
		
	    try
        {
            $siol_epgs = $this->epg->GetEpg($url, $day_start_tm_sec, $day_str, $channel_str, $plugin_cookies->SiolPluginShowEpgDetails);
			//$siol_epgs = $this->epg->GetEpg($url, $day_start_tm_sec, $day_str, $channel_str, 'no');
        }
        catch (Exception $e)
        {
			//TODO:
            //throw $this->dune_api_exception($e, T::t('siol_plugin_epg_request_failed'), true);
        }


	    foreach ($siol_epgs as $siol_epg)
        {
			//TODO: odstej zamik - trenutni je 2 uri = 7200
            $start = intval($siol_epg->StartTime) - 7200;
            $end = -1;
			
			$newEpgProgram = new PluginTvEpgProgram();
			$newEpgProgram->name = $siol_epg->Name;
			$newEpgProgram->description = $siol_epg->Description;
			$newEpgProgram->start_tm_sec = $start;
			$newEpgProgram->end_tm_sec = $end;
            $epg_program[] = $newEpgProgram;
        }		
		
		return $epg_program;
	}
	
	// PluginTvInfo
	public function get_tv_info(
	/* [in]     String                      */ MediaURL $media_url,
	/* [inout]  Map: Key -> Value           */  &$plugin_cookies)
	{
		hd_print('get_tv_info invoked.');
		return parent::get_tv_info($media_url, &$plugin_cookies);
	}
	
	// String 
    public function get_tv_playback_url(
        /* [in]     String                      */  $channel_id,
        /* [in]     int                         */  $archive_tm_sec,
        /* [in]     String                      */  $protect_code,
        /* [inout]  Map: Key -> Value           */  &$plugin_cookies)
	{
		hd_print('get_tv_playback_url invoked.');
		$SiolPluginParentCode = isset($plugin_cookies->SiolPluginParentCode) ?
			$plugin_cookies->SiolPluginParentCode : '';
			hd_print("get_tv_playback_url check code. protect_code=$protect_code, SiolPluginParentCode=$SiolPluginParentCode");
		if (!isset($protect_code) || $protect_code == $SiolPluginParentCode)
		{
			return parent::get_tv_playback_url($channel_id, $archive_tm_sec, $protect_code, &$plugin_cookies);
		}
		else
		{
			hd_print("Blocked channel: $channel_id");
			return 'protected';
		}
		
		return parent::get_tv_playback_url($channel_id, $archive_tm_sec, $protect_code, &$plugin_cookies);
	}

	public function get_all_channel_group_id()
	{
		//hd_print('get_all_channel_group_id invoked.');
		return parent::get_all_channel_group_id();
	}
	
	public function get_channels()
	{
		hd_print('get_channels invoked.');
		return parent::get_channels();
	}
	
	public function get_channel($channel_id)
	{
		hd_print("get_channel invoked. id=$channel_id");
		return parent::get_channel($channel_id);
	}
	
	public function get_groups()
	{
		hd_print('get_groups invoked.');
		return parent::get_groups();
	}
	
	public function get_group($group_id)
	{
		hd_print("get_group invoked. id=$group_id");
		return parent::get_channel($group_id);
	}
	
    ///////////////////////////////////////////////////////////////////////

    public function get_tv_group_list_folder_views(&$plugin_cookies)
    {
        return SiolConfig::GET_TV_GROUP_LIST_FOLDER_VIEWS();
    }

    public function get_tv_channel_list_folder_views(&$plugin_cookies)
    {
        return SiolConfig::GET_TV_CHANNEL_LIST_FOLDER_VIEWS();
    }

}

///////////////////////////////////////////////////////////////////////////
?>
